package com.mmc.service.impl;


import com.alibaba.fastjson.JSON;
import com.mmc.client.ContentClient;
import com.mmc.entity.Content;
import com.mmc.service.PortalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者：李嘉浩
 * 时间：2024-09-16-16:47
 * 功能：
 */
@Service
public class PortalServiceImpl implements PortalService {
    @Autowired
    private ContentClient contentClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<Content> findByCategoryId(long l) {
        List<Content> list=new ArrayList<>();
        Cursor<Map.Entry<Object, Object>> scan = stringRedisTemplate.opsForHash().scan("content_map", ScanOptions.NONE);
        if (scan.hasNext()){
            while (scan.hasNext()){
                Map.Entry<Object, Object> next = scan.next();
                list.add(JSON.parseObject((String) next.getValue(),Content.class));
            }
        }else {
            list=contentClient.findByCategoryId(l);
            for (Content content:list){
                stringRedisTemplate.opsForHash().put("content_map",content.getId()+"",JSON.toJSONString(content));
            }
        }
        return list;
    }
}
